package com.ruoyi.common.datascope.aspect;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.BaseEntity;
import com.ruoyi.common.datascope.annotation.ShopDataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 店铺过滤处理
 *
 */
@Aspect
@Component
public class ShopDataScopeAspect {
    /**
     * 门店过滤关键字
     */
    public static final String SHOP_DATA_SCOPE = "shopDataScope";

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, ShopDataScope controllerDataScope) throws Throwable
    {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }
    protected void handleDataScope(final JoinPoint joinPoint, ShopDataScope controllerDataScope)
    {
        String sqlString = "";
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser))
        {
            SysUser currentUser = loginUser.getSysUser();
            //添加dime管理员排除 Added By Lance
            sqlString = String.format(" AND ( {}.shop_code = {} )",controllerDataScope.shopAlias(), SecurityUtils.getShopId());
            if(StringUtils.isNotBlank(sqlString)) {
                Object params = joinPoint.getArgs()[0];
                if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                    BaseEntity baseEntity = (BaseEntity) params;
                    baseEntity.getParams().put(SHOP_DATA_SCOPE,  sqlString);
                }
            }
        }
    }
    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint)
    {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
        {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(SHOP_DATA_SCOPE, "");
        }
    }
}
